package cat

import (
	"cat-collage-backend/internal/model"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"strconv"
)

type catResponse struct {
	Msg  string                `json:"msg"`
	Data []catResponseDataItem `json:"data"`
}

type catResponseDataItem struct {
	Cat       model.Cat           `json:"cat"`
	CatHobbys []model.CatHobby    `json:"catHobbys"`
	CatImages []model.CatImage    `json:"catImages"`
	CatPos    []model.CatPosition `json:"catPos"`
}

func GetAllCats(c *gin.Context, db *gorm.DB) {
	// 获取查询参数，如果未提供，则使用默认值
	limitStr := c.DefaultQuery("limit", "10")
	pageStr := c.DefaultQuery("page", "1")

	// 将字符串参数转换为整数
	limit, err := strconv.Atoi(limitStr)
	if err != nil {
		// 处理错误或设置为另一个默认值
		limit = 10
	}

	page, err := strconv.Atoi(pageStr)
	if err != nil {
		// 处理错误或设置为另一个默认值
		page = 1
	}

	offset := (page - 1) * limit

	cats := make([]model.Cat, 0)
	catHobbys := make([]model.CatHobby, 0)
	catImages := make([]model.CatImage, 0)
	catPos := make([]model.CatPosition, 0)

	db.Limit(limit).Offset(offset).Find(&cats)
	if len(cats) == 0 {
		c.JSON(200, gin.H{"error": "Cat not found", "data": nil})
		return
	}
	catIds := make([]string, len(cats))
	for i, cat := range cats {
		catIds[i] = cat.ID
	}
	db.Where("cat_id IN ?", catIds).Find(&catHobbys)
	db.Where("cat_id IN ?", catIds).Find(&catImages)
	db.Where("cat_id IN ?", catIds).Find(&catPos)
	r := &catResponse{}
	for _, cat := range cats {
		item := catResponseDataItem{
			Cat:       cat,
			CatHobbys: make([]model.CatHobby, 0),
			CatImages: make([]model.CatImage, 0),
			CatPos:    make([]model.CatPosition, 0),
		}
		for _, catHobby := range catHobbys {
			if catHobby.CatId == item.Cat.ID {
				item.CatHobbys = append(item.CatHobbys, catHobby)
			}
		}
		for _, catImage := range catImages {
			if catImage.CatId == item.Cat.ID {
				item.CatImages = append(item.CatImages, catImage)
			}
		}
		for _, catPo := range catPos {
			if catPo.CatId == item.Cat.ID {
				item.CatPos = append(item.CatPos, catPo)
			}
		}
		r.Data = append(r.Data, item)
	}

	c.JSON(200, gin.H{"msg": "success", "data": r})
}
